import { defineStore } from 'pinia'
import type { LearningResource as Resource, ResourceType } from '@/types/resource'
import type { Category } from '@/types/index'
import { searchResources, getResourceDetail as getResourceById, downloadResource, favoriteResource, getFavoriteResources, getResourceCategories } from '@/api/resource'

interface ResourcesState {
  resources: (Resource & { isFavorite?: boolean })[]
  resource: (Resource & { isFavorite?: boolean }) | null
  categories: Category[]
  favoriteResources: (Resource & { isFavorite?: boolean })[]
  pagination: {
    currentPage: number
    total: number
    pageSize: number
  }
  isLoading: boolean
  error: string | null
  downloadProgress: number | null
}

export const useResourcesStore = defineStore('resources', {
  state: (): ResourcesState => ({
    resources: [],
    resource: null,
    categories: [],
    favoriteResources: [],
    pagination: {
      currentPage: 1,
      total: 0,
      pageSize: 10
    },
    isLoading: false,
    error: null,
    downloadProgress: null
  }),
  
  getters: {
    // 根据分类获取资源
    resourcesByCategory: (state) => (categoryId: number) => {
      if (!categoryId) return state.resources
      return state.resources.filter(resource => resource.category?.id === categoryId)
    },
    
    // 根据类型获取资源
    resourcesByType: (state) => (type: ResourceType) => {
      if (!type) return state.resources
      return state.resources.filter(resource => resource.type === type)
    },
    
    // 获取热门资源（下载量最高的）
    hotResources: (state): Resource[] => {
      return [...state.resources]
        .sort((a, b) => (b.downloadCount || 0) - (a.downloadCount || 0))
        .slice(0, 5)
    }
  },
  
  actions: {
    // 获取资源列表
    async fetchResources(params?: {
      keyword?: string
      categoryId?: number
      type?: ResourceType
      sortBy?: 'downloads' | 'views' | 'rating' | 'createdAt'
      sortOrder?: 'asc' | 'desc'
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await searchResources(params || {})
        this.resources = response.items || []
        this.pagination = {
          currentPage: response.currentPage || 1,
          total: response.total || 0,
          pageSize: response.pageSize || 10
        }
        return response
      } catch (error: any) {
        this.error = error.message || '获取资源列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取单个资源详情
    async fetchResourceById(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const response = await getResourceById(id)
        this.resource = response
        return response
      } catch (error: any) {
        this.error = error.message || '获取资源详情失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 下载资源
    async downloadResource(id: number) {
      try {
        this.isLoading = true
        this.downloadProgress = 0
        // 模拟下载进度
        const interval = setInterval(() => {
          if (this.downloadProgress !== null && this.downloadProgress < 100) {
            this.downloadProgress += 10
          } else {
            clearInterval(interval)
            this.downloadProgress = null
          }
        }, 300)
        
        const response = await downloadResource(id)
        
        // 清除进度模拟
        clearInterval(interval)
        this.downloadProgress = null
        
        // 更新下载次数
        const resource = this.resources.find(r => r.id === id)
        if (resource) {
          resource.downloadCount = (resource.downloadCount || 0) + 1
        }
        if (this.resource && this.resource.id === id) {
          this.resource.downloadCount = (this.resource.downloadCount || 0) + 1
        }
        
        return response
      } catch (error: any) {
        this.error = error.message || '下载资源失败'
        this.downloadProgress = null
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 收藏/取消收藏资源
    async toggleFavorite(id: number) {
      try {
        this.isLoading = true
        const result = await favoriteResource(id)
        
        // 更新资源的收藏状态
        const resource = this.resources.find(r => r.id === id)
        if (resource) {
          resource.isFavorite = result.isFavorite
          resource.favoriteCount = (resource.favoriteCount || 0) + (result.isFavorite ? 1 : -1)
        }
        if (this.resource && this.resource.id === id) {
          this.resource.isFavorite = result.isFavorite
          this.resource.favoriteCount = (this.resource.favoriteCount || 0) + (result.isFavorite ? 1 : -1)
        }
        
        // 刷新收藏列表
        await this.fetchFavoriteResources({ page: 1, pageSize: 10 })
        
        return result
      } catch (error: any) {
        this.error = error.message || '操作失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取收藏资源列表
    async fetchFavoriteResources(params: { page?: number; pageSize?: number } = { page: 1, pageSize: 10 }) {
      try {
        this.isLoading = true
        const result = await getFavoriteResources(params)
        this.favoriteResources = result.items || []
        return result
      } catch (error: any) {
        console.error('获取收藏资源失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取资源分类
    async fetchCategories() {
      try {
        this.isLoading = true
        const categories = await getResourceCategories()
        this.categories = categories
        return categories
      } catch (error: any) {
        console.error('获取资源分类失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 清除资源详情
    clearResourceDetail() {
      this.resource = null
    },
    
    // 重置下载进度
    resetDownloadProgress() {
      this.downloadProgress = null
    }
  }
})